#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash bwa-0.7.17.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
sudo yum install -y wget tar environment-modules libatomic \
zlib-devel
source /etc/profile

  echo "# bwa-0.7.17正在下载"
  wget -t 10 -T 20 -c -P $buildpath \
    https://github.com/lh3/bwa/archive/refs/tags/v0.7.17.tar.gz
  
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# bwa-0.7.17 已经下载成功\033[0m"
  else
    echo -e "\033[31m# bwa-0.7.17 下载失败,请重新执行脚本\033[0m"
    exit 1
  fi

  echo "# bwa-0.7.17 正在安装"
  tar -xzf $buildpath/v0.7.17.tar.gz -C $buildpath && rm -rf $buildpath/v0.7.17.tar.gz
  cd $buildpath/bwa-0.7.17

  cp -r $buildpath/sse2neon.h $buildpath/bwa-0.7.17

  sed -i "s/gcc/clang/" Makefile
  sed -i "29c #include \"sse2neon.h\"" ksw.c
  sed -i "33c extern const uint8_t rle_auxtab[8];" rle.h
  make -j$(nproc)
  mkdir -p $installpath/bwa-0.7.17
  cp -a ./* $installpath/bwa-0.7.17
  echo -e "\033[1;32;1m# bwa-0.7.17 已经安装完毕\033[0m"

 cat >"$installpath/bwa-0.7.17/bwa_modulefiles" <<EOF
#%Module1.0
conflict bwa
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set BWA \$pwd
setenv BWA \$BWA
prepend-path PATH \$BWA
EOF

rm -rf $buildpath/bwa-0.7.17
